package longrise.phone.com.bjjt_henan.main;

import android.app.Activity;
import android.content.Context;
import android.location.LocationManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.LFView;
import com.longrise.android.listview_library_refrush.PullToRefreshBase;
import com.longrise.android.listview_library_refrush.PullToRefreshScrollView;
import com.longrise.bjjt.util.PrefUtils;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Constant.MsgConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.Utils.PermissionHelper;
import longrise.phone.com.bjjt_henan.bindinginformation.BindCarView;
import longrise.phone.com.bjjt_henan.compensate.OpenGpsView;
import longrise.phone.com.bjjt_henan.compensate.SafeWarningView;
import longrise.phone.com.bjjt_henan.myaccident.AccidentMainView;
import longrise.phone.com.bjjt_henan.widget.DealDialog;

/**
 * 快处快赔项页面
 */
public class NewKckpView extends LFView implements View.OnClickListener {

    private View mView;

    private Context mContext;

    private LinearLayout trafficLayout;

    private LinearLayout operationLayout;

    private RelativeLayout kckpLayout;

    private LinearLayout caseLayout;

    private int bindState;//绑定状态

    private boolean isClick = false;

    private LFView view;

    private RollImageView rollImageView;

    private PullToRefreshScrollView scrollView;

    private boolean isLoading = false;// 正在刷新

    private TextView dotTV;

    private EntityBean entityBean;

    private DealDialog dealDialog;

    public NewKckpView(Context context) {
        super(context);
        this.mContext = context;
    }

    public void setBindState(int bindState) {
        this.bindState = bindState;
        if (isClick) {
            isClick = false;
            checkData();
        }
    }

    public void setBindBean(EntityBean bindBean) {
        this.entityBean = bindBean;
    }

    public void setView(LFView view) {
        this.view = view;
    }

    @Override
    public View getView() {
        return mView;
    }

    @Override
    public FormParameter getFormParameter() {
        return null;
    }

    @Override
    public void init() {
        if (mContext == null) {
            return;
        }
        mView = LayoutInflater.from(mContext).inflate(R.layout.view_newkckp, null);
        if (mView == null) {
            return;
        }
        trafficLayout = (LinearLayout) mView.findViewById(R.id.newkckp_layout_traffic);
        operationLayout = (LinearLayout) mView.findViewById(R.id.newkckp_layout_operation);
        kckpLayout = (RelativeLayout) mView.findViewById(R.id.newkckp_layout_kckp);
        caseLayout = (LinearLayout) mView.findViewById(R.id.newkckp_layout_histroycase);
        scrollView = (PullToRefreshScrollView) mView.findViewById(R.id.pull_refresh_scrollview);
        dotTV = (TextView) mView.findViewById(R.id.newkckp_tv_flash);
        initRefreshView();
        initRollView();
        setViewSize();
        showFlash();

        setListen(true);
    }

    //轮播图片界面
    private void initRollView() {
        LinearLayout imgLayout = (LinearLayout) mView.findViewById(R.id.newkckp_layout_imgs);
        setImgSize(imgLayout);
        if (rollImageView == null) {
            rollImageView = new RollImageView(mContext);
            rollImageView.setNewsType("2");
            rollImageView.setListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkCarInfo();
                }
            });
            rollImageView.init();
            rollImageView.refresh();
        }
        imgLayout.removeAllViews();
        imgLayout.addView(rollImageView.getView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
    }

    private void checkCarInfo() {
        if (bindState == -1) {
            UiUtil.showToast(mContext, "数据加载有误,请稍后重试！");
            LSMsgCall(99, "bindinfo");
            return;
        }
        EntityBean[] cars = null;
        if (entityBean != null) {
            cars = entityBean.getBeans("car");
        }
        if (null == cars || cars.length < 1) {//未绑定车辆
            if (dealDialog == null) {
                dealDialog = new DealDialog(mContext);
                dealDialog.setInfo(R.string.bind_car);
                dealDialog.setCancel("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dealDialog.dismiss();
                    }
                });
                dealDialog.setConfirm("绑定车辆", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dealDialog.dismiss();
                        BindCarView bindcarview = new BindCarView(mContext, null);
                        FrameworkManager.getInstance().showNewForm(mContext, bindcarview);
                    }
                });
            }
            dealDialog.show();
            return;
        }
        SelectCarView carView = new SelectCarView(mContext, cars);
        carView.setType(0);
        FrameworkManager.getInstance().showNewForm(mContext, carView);
    }

    private void setImgSize(LinearLayout layout) {
        //取得当前屏幕的长宽
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int height = Math.round(screenWidth * 2.0f / 5);//设定图片的宽高比
        LinearLayout.LayoutParams imgP = (LinearLayout.LayoutParams) layout.getLayoutParams();
        imgP.width = screenWidth;
        imgP.height = height;
        layout.setLayoutParams(imgP);
        imgP = null;
    }

    //显示动画效果
    private void showFlash() {
        if (mView == null) {
            return;
        }
        //缩放动画
        Animation scale = new ScaleAnimation(1.0f, 0.8f, 1.0f, 0.8f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scale.setDuration(800);
        scale.setRepeatMode(Animation.REVERSE);
        scale.setRepeatCount(Animation.INFINITE);
        //渐变动画
        AlphaAnimation alpha = new AlphaAnimation(1.0f, 0.7f);
        alpha.setDuration(800);
        scale.setRepeatMode(Animation.REVERSE);
        alpha.setRepeatCount(Animation.INFINITE);

        AnimationSet set = new AnimationSet(true);
        set.addAnimation(scale);
        set.addAnimation(alpha);

        dotTV.startAnimation(set);
    }

    private void initRefreshView() {
        // 刚拉时的提示
        scrollView.getLoadingLayoutProxy().setPullLabel("加载列表数据...");
        // 正在刷新提示
        scrollView.getLoadingLayoutProxy().setRefreshingLabel("正在载入...");
        // 拉倒一定高度的提示
        scrollView.getLoadingLayoutProxy().setReleaseLabel("放开以刷新...");
        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (!isLoading) {
                    if (rollImageView != null) {//刷新新闻
                        rollImageView.refresh();
                    }
                    LSMsgCall(99, "bindinfo");//刷新用户的信息
                }
            }
        });
    }

    public void finishRefresh() {
        if (null != scrollView) {// 停止刷新
            scrollView.onRefreshComplete();
        }
    }

    //重新计算布局的宽高
    private void setViewSize() {
        int[] size = CommontUtils.getViewSize(mContext, R.mipmap.traffic, 10);
        int width = size[0];
        int height = size[1];

        LinearLayout.LayoutParams trafficP = (LinearLayout.LayoutParams) trafficLayout.getLayoutParams();
        trafficP.width = width;
        trafficP.height = height;
        trafficLayout.setLayoutParams(trafficP);
        trafficP = null;
        LinearLayout.LayoutParams operationP = (LinearLayout.LayoutParams) operationLayout.getLayoutParams();
        operationP.width = width;
        operationP.height = height;
        operationLayout.setLayoutParams(operationP);
        operationP = null;
        LinearLayout.LayoutParams kckpP = (LinearLayout.LayoutParams) kckpLayout.getLayoutParams();
        kckpP.width = width;
        kckpP.height = height;
        kckpLayout.setLayoutParams(kckpP);
        kckpP = null;
        LinearLayout.LayoutParams caseP = (LinearLayout.LayoutParams) caseLayout.getLayoutParams();
        caseP.width = width;
        caseP.height = height;
        caseLayout.setLayoutParams(caseP);
        caseP = null;
    }

    private void setListen(boolean flag) {
        if (trafficLayout != null) {
            trafficLayout.setOnClickListener(flag ? this : null);
        }
        if (operationLayout != null) {
            operationLayout.setOnClickListener(flag ? this : null);
        }
        if (kckpLayout != null) {
            kckpLayout.setOnClickListener(flag ? this : null);
        }
        if (caseLayout != null) {
            caseLayout.setOnClickListener(flag ? this : null);
        }
    }

    @Override
    public void onClick(View v) {
        LFView mView = null;
        switch (v.getId()) {
            case R.id.newkckp_layout_operation://操作演示
                StatService.onEvent(mContext, "operation_demo", "操作演示");
                mView = new ActionDemoView(mContext);
                break;
            case R.id.newkckp_layout_histroycase://历史案件
                StatService.onEvent(mContext, "histroy_case", "历史案件");
                PrefUtils.setBoolean(mContext, MsgConstant.HISTORY_CASE, true);
                AccidentMainView accidentView = new AccidentMainView(mContext);
                int level = FrameworkManager.getInstance().showNewForm(mContext, accidentView);
                ((MainActivity) mContext).getAppLike().setHistroyLevel(level);
                break;
            case R.id.newkckp_layout_kckp://快处快赔
                StatService.onEvent(mContext, "kckp", "快处快赔");
                checkTime();
                break;
            case R.id.newkckp_layout_traffic://出行服务
                if (!PermissionHelper.checkLocPermissions(mContext)) {
                    return;
                }
                StatService.onEvent(mContext, "traffic_service", "出行服务");
                mView = new TravelServiceView(mContext);
                break;
            default:
                break;
        }
        if (null != mView) {
            FrameworkManager.getInstance().showNewForm(mContext, mView);
        }
    }

    private void checkData() {
        if (bindState == -1) {//查询数据失败则重新查询
            LSMsgCall(99, "bindinfo");
            isClick = true;//点击后如果数据加载正确则直接进入下一步流程
            return;
        }
        //判断是否打开gps，没有打开跳转到提示打开gps界面，已经打开进入安全提示,获取areaid并存入application中
        if (bindState == 1) {//已经绑定信息，进入下个流程
            PrefUtils.setBoolean(mContext, MsgConstant.HISTORY_CASE, false);
            LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
            if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                //跳转到提示打开gps界面
                OpenGpsView opengpsview = new OpenGpsView(mContext);
                FrameworkManager.getInstance().showNewForm(mContext, opengpsview);
            } else {
                //跳转到安全提示界面
                SafeWarningView safewarningview = new SafeWarningView(mContext);
                FrameworkManager.getInstance().showNewForm(mContext, safewarningview);
            }
        } else {
            //没有绑定信息，提示先绑定信息
            if (view != null && view instanceof NewMainView) {
                ((NewMainView) view).showBindDialog();
            }
        }
    }

    /**
     * 判断是否在允许的时间内
     */
    private void checkTime() {
        DialogUtils.showDialog(mContext);
        String userflag = ((MainActivity) mContext).getAppData().getKckpName();
        String token = ((MainActivity) mContext).getAppData().getToken();
        ApiImpI.getInstance(mContext).checkTime(userflag, token, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(mContext, error);
                }
            }

            @Override
            public void onSuccess(Object result) {
                DialogUtils.closeDialog();
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if (TextUtils.equals("1", restate)) {
                    EntityBean dataBean = bean.getBean("data");
                    if (null != dataBean) {
                        String isTrue = dataBean.getString("istrue");
                        if (TextUtils.equals("1", isTrue)) {
                            checkData();
                            return;
                        }
                    }
                }
                String redes = bean.getString("redes");
                UiUtil.showToast(mContext, redes);
            }
        });
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void refresh() {
        if (dotTV != null) {
            Animation animation = dotTV.getAnimation();
            if (animation == null) {
                showFlash();
            }
        }
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        setListen(false);
        if (null != rollImageView) {
            rollImageView.OnDestroy();
            rollImageView = null;
        }
        mView = null;
    }
}
